<template>
  <div class="form_box">
    <div class="header">
      <a-breadcrumb>
        <a-breadcrumb-item
          ><a @click="navBack">返回上一页</a></a-breadcrumb-item
        >
        <a-breadcrumb-item>发布资源</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-form
      :model="formState"
      name="basic"
      autocomplete="off"
      @finish="onFinish"
      layout="vertical"
    >
      <a-form-item
        label="任务名称"
        name="pu_title"
        :rules="[
          { required: true, message: '请输入任务名称', trigger: 'change' },
        ]"
      >
        <a-input
          v-model:value="formState.pu_title"
          placeholder="请填写名称"
          show-count
          :maxlength="15"
        />
      </a-form-item>

      <a-form-item label="信息图片（包含订单，联系方式等重要信息 不超过五张）" name="imgList"   :rules="[
            { required: true, validator: validateImg, trigger: 'change' },
          ]">
        <upload
          @uploadRes="uploadRes"
          :maxCount="5"
        
        ></upload>
      </a-form-item>
      <a-form-item
        label="平台"
        name="pu_platform"
        :rules="[{ required: true, message: '请选择平台', trigger: 'change' }]"
      >
        <a-select
          v-model:value="formState.pu_platform"
          :options="state.platformData"
          size="middle"
          placeholder="请选择平台"
          :field-names="{ label: 'name', value: 'id' }"
        ></a-select>
      </a-form-item>
      <a-form-item
        label="地区"
        name="address"
        :rules="[{ required: true, message: '请填写地区', trigger: 'change' }]"
      >
        <a-cascader
          :show-search="{ filter }"
          v-model:value="formState.address"
          :options="proxyCityData"
          placeholder="请选择任务派往地区"
          :fieldNames="{ label: 'name', value: 'code', children: 'children' }"
        />
      </a-form-item>
      <!-- <a-form-item label="设置费用" name="pu_tip" :rules="[{ required: true, message: '请输入任务名称111', trigger: 'change' }]">
        <a-input v-model="formState.pu_tip" placeholder="请输入费用" type="number" />
      </a-form-item> -->
      <a-form-item label="茶水费（会有人更快帮助哦 最多不超过1000）" name="pu_tip">
        <a-input
          v-model:value="formState.pu_tip"
          placeholder="请输入费用"
          type="number"
        />
      </a-form-item>
      <a-form-item
        label="结束时间（您的预计结束时间）"
        name="pu_finish_time"
        :rules="[
          { required: true, message: '请选择结束时间', trigger: 'change' },
        ]"
      >
        <a-config-provider :locale="zhCN">
          <a-date-picker
            v-model:value="pu_finish_time"
            format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
            @change="changeDate"
          />
        </a-config-provider>
      </a-form-item>

      <a-form-item
        label="备注信息（请描述您所遇到的问题，最多不超过80字）"
        name="pu_description"
        :rules="[
          { required: true, message: '请选择结束时间', trigger: 'change' },
        ]"
      >
        <a-textarea
          v-model:value="formState.pu_description"
          placeholder="请描述详细信息"
          :rows="4"
          show-count
          :maxlength="80"
        />
      </a-form-item>
      <a-form-item>
        <div style="text-align: center">
          <a-button type="primary" html-type="submit" size="large" block
            >发布</a-button
          >
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, getCurrentInstance, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import dayjs, { Dayjs } from "dayjs";
import { PlusOutlined } from "@ant-design/icons-vue";
import type { CascaderProps } from "ant-design-vue";
import type { ShowSearchType } from "ant-design-vue/es/cascader";
import { publishOperate } from "@/api/mutualaid/index";
import upload from "../../../components/upload/index.vue";
import publishListMethod from "@/hooks/type/index";
import cityData from "@/data/city/index";

import zhCN from "ant-design-vue/es/locale/zh_CN";

import "dayjs/locale/zh-cn";
dayjs.locale("en");

const router = useRouter();
const appCurrent = getCurrentInstance();
const address = ref<string[]>([]);
const pu_finish_time = ref<Dayjs>();
const flidata = reactive({
  path: "avatar",
});

const state = reactive({
  platformData: [] as any[],
});
const key = "加载中";

const changeDate = (date: any) => {
  formState.pu_finish_time = date.format("YYYY-MM-DD");
};
const range = (start: number, end: number) => {
  const result = [];

  for (let i = start; i < end; i++) {
    result.push(i);
  }

  return result;
};

const disabledDate = (current: Dayjs) => {
  // Can not select days before today and today
  return current && current < dayjs().endOf("day");
};

onMounted(() => {
  publishListMethod().then((res) => {
    state.platformData = res;
  });
});

const proxyCityData: CascaderProps["options"] = cityData;

const storageImgList = reactive({ imgList: [] });
interface FormState {
  pu_userId: string;
  pu_title: string;
  pu_order_screenshot: string;
  pu_tip: number | string;
  pu_finish_time: Dayjs | string;
  pu_receiver: number | string;
  pu_type: number | string;
  pu_description: number | string;
  pu_platform: any;
  pu_province_id: string;
  pu_city_id: string;
  pu_district_id: string;
  address: any;
}

const formState = reactive<FormState>({
  pu_userId:
    JSON.parse(window.localStorage.getItem("userInfo") || "{}").id || {},
  pu_title: "",
  pu_order_screenshot: "",
  pu_platform: parseInt(router.currentRoute.value.query.type as string) || null,
  pu_tip: "",
  pu_receiver: 0,
  pu_finish_time: "",
  pu_description: "",
  pu_type: 1,
  pu_province_id: "",
  pu_city_id: "",
  pu_district_id: "",
  address: "",
});

const filter: ShowSearchType["filter"] = (inputValue, path) => {
  return path.some((option) => {
    return option.name.indexOf(inputValue) > -1;
  });
};

const uploadRes = (file: string) => {
  
  formState.pu_order_screenshot = file.toString();
  // storageImgList.imgList = file;
};
const validateImg = (rule: any, value: string) => {
    if (formState.pu_order_screenshot.split(',').length === 0 || formState.pu_order_screenshot.split(',').length > 5){
      return Promise.reject('请上传图片并且不能超过5张');
    }
    return Promise.resolve();
  };
const changeTime = (time: any) => {
  
};

const onFinish = async (values: any) => {
  formState.pu_province_id = formState.address[0];
  formState.pu_city_id = formState.address[1];
  formState.pu_district_id = formState.address[2];

  message.loading({ content: "Loading...", key });

  if (formState.pu_order_screenshot.length == 0)
    return message.error({ content: "请上传图片!", key, duration: 2 });

  delete formState.address;

  const res = await publishOperate(formState);

  if (res.data.code != 0)
    return message.error({
      content: res.data.msg,
      key,
      duration: 2,
    });
  message.success({
    content: "发布成功",
    key,
    duration: 2,
  });
  router.push({ path: "/" });
};

const onFinishFailed = (errorInfo: any) => {
  

  message.loading({ content: "Loading...", key });
  setTimeout(() => {
    message.error({ content: "发布失败!", key, duration: 2 });
  });
};

const navBack = () => {
  router.go(-1);
};
</script>
<style lang="scss" scoped>
.form_box {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 30px;

  .header {
    margin: 30px 0;
  }
}

.ant-upload-text {
  width: 128px;
  height: 128px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px solid #eee;
  border-radius: 20px;
}
</style>